#!/bin/bash
:<<!
打包脚本
!
#sh all_packing_ios.sh -p "${PlatformType}" -b $BRANCH -pt "${PackageTargetType}" -pn "${PackageNetworkType}" -d "${ChangeLog}" --pgyerUploadUrlType ${PgyerUploadUrlType} --shouldBackupToCos ${ShouldBackupToCos} --shouldUploadToAppStore ${ShouldUploadToAppStore} -np $NotificatePeople
#sh all_packing_ios.sh -p iOS -b origin/dev_all -pt "生成最后只发布到蒲公英的包" -pn "开发" -d "更新说明略\n分支信息:\ndev_fix:功能修复" --pgyerUploadUrlType "直接上传到最终地址" --shouldBackupToCos false --shouldUploadToAppStore false -np none
#sh all_packing_ios.sh -p iOS -b dev_all -pt "生成最后只发布到蒲公英的包" -pn "测试" -d "测试脚本，请勿下载" --pgyerUploadUrlType "直接上传到最终地址" --shouldBackupToCos false --shouldUploadToAppStore false -np none
#sh all_packing_ios.sh -p iOS -b dev_publish_in -pt "生成最后只发布到蒲公英的包" -pn "预生产" -d "更新说明略分支信息:dev_fix:功能修复" --pgyerUploadUrlType "直接上传到最终地址" --shouldBackupToCos false --shouldUploadToAppStore false -np all
#sh all_packing_ios.sh -p iOS -b dev_publish_in -pt "生成最后只发布到TestFlight的包" -pn "生产" -d "更新说明略\n分支信息:\ndev_fix:功能修复" --pgyerUploadUrlType "先上传到临时地址，通过后再添加到最终地址" --shouldBackupToCos true --shouldUploadToAppStore false -np all
#sh all_packing_ios.sh -p Android -b dev_publish_out -pt "生成最后要发布到AppStore的包" -pn "生产" -d "更新说明略\n分支信息:\ndev_fix:功能修复" --pgyerUploadUrlType "不上传" --shouldBackupToCos true --shouldUploadToAppStore true -np all
# 更新说明有换行，暂时还不支持
User=`whoami`

JQ_EXEC=`which jq`

# shell 参数具名化
show_usage="args: [-p , -b , -pt , -pn , -d , -upPgyer, -supCos, -supAppStore, -np]\
                                  [--platformType=, --feature-branch=, --package_target_type=, --package_network_type=, --update-description=, --pgyerUploadUrlType=,--shouldBackupToCos=,--shouldUploadToAppStore=, --notificate-forPeople=]"

while [ -n "$1" ]
do
        case "$1" in
                -p|--platformType) PlatformType=$2; shift 2;;
                -b|--feature-branch) BRANCH=$2; shift 2;;
                -pt|--package_target_type) PackageTargetType=$2; shift 2;;
                -pn|--package_network_type) PackageNetworkType=$2; shift 2;;
                -d|--update-description) ChangeLog=$2; shift 2;;
                -upPgyer|--pgyerUploadUrlType) PgyerUploadUrlType=$2; shift 2;;
                -supCos|--shouldBackupToCos) ShouldBackupToCos=$2; shift 2;;
                -supAppStore|--shouldUploadToAppStore) ShouldUploadToAppStore=$2; shift 2;;
                -np|--notificate-forPeople) NotificatePeople=$2; shift 2;;
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done



# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'

ShouldBackupToLocal="true"


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


#if [ $# != 5 ]; then
#    echo "当前参数个数$#，必须为5个，请设置更新说明"
#    exit 1
#fi

CUR_DIR="$( cd "$( dirname "$0" )" && pwd )"
#WORKSPACE=$CUR_DIR/..
WORKSPACE="${CUR_DIR%/*}" # 使用此方法可以避免路径上有..
echo "WORKSPACE=$WORKSPACE"


# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
bulidScriptApp_dir_Absolute=${CurrentDIR_Script_Absolute}
echo "bulidScriptApp_dir_Absolute=${bulidScriptApp_dir_Absolute}"


FILE_PATH="${bulidScriptApp_dir_Absolute}/app_info.json"

echo "FILE_PATH=$FILE_PATH"
echo "PlatformType=$PlatformType"
echo "BRANCH=$BRANCH"
echo "PackageTargetType=$PackageTargetType"
echo "PackageNetworkType=$PackageNetworkType"
echo "ChangeLog=$ChangeLog"
echo "User=$User"
#echo "结束"


cd ${WORKSPACE}
BUILD_SCRIPT_PRODUCT_DIR_NAME="buildScriptSource"
BUILD_SCRIPT_PRODUCT_DIR_PATH="${WORKSPACE}/${BUILD_SCRIPT_PRODUCT_DIR_NAME}"
function upgradeScript() {
    if [ -d "${BUILD_SCRIPT_PRODUCT_DIR_PATH}" ]; then
        rm -rf "${BUILD_SCRIPT_PRODUCT_DIR_PATH}"
        if [ $? != 0 ]; then
            echo "❌Error:rm 操作失败，请检查！"
            exit_script
        fi
    fi
    CommitInfoScriptVersion=0.4.0
    echo "正在执行命令(拉取脚本代码):《 git clone -b \"${CommitInfoScriptVersion}\" https://gitee.com/dvlpCI/AutoPackage-CommitInfo \"${BUILD_SCRIPT_PRODUCT_DIR_NAME}\" 》"
    git clone -b "${CommitInfoScriptVersion}" https://gitee.com/dvlpCI/AutoPackage-CommitInfo "${BUILD_SCRIPT_PRODUCT_DIR_NAME}"
    if [ $? != 0 ]; then
        echo "❌Error:git 操作失败，请检查！"
        exit_script
    fi
}
NEED_UPDATE_SCRIPT="false" # 是否需要每次更新
if [ "${NEED_UPDATE_SCRIPT}" == "true" ]; then
    upgradeScript
fi

bulidScriptCommon_dir_Absolute="${BUILD_SCRIPT_PRODUCT_DIR_PATH}/bulidScriptCommon"
echo "bulidScriptCommon_dir_Absolute=${bulidScriptCommon_dir_Absolute}"
cd ${bulidScriptCommon_dir_Absolute}


qscript_path_get_filepath="${bulidScriptCommon_dir_Absolute}/qscript_path_get.sh"
qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_sed_text_script_path="$(sh ${qscript_path_get_filepath} qbase sedtext)"
qbase_json_file_check_script_path="$(sh ${qscript_path_get_filepath} qbase json_file_check)"


addAppHistoryVerisonJsonFile() {
    History_Versions_FILE_PATH="${bulidScriptApp_dir_Absolute}/app_history_version.json"
    if [ ! -f "${History_Versions_FILE_PATH}" ];then
        echo "❌:您的History_Versions_FILE_PATH=${History_Versions_FILE_PATH}文件不存在，请检查！"
        exit_script
    fi
    sh ${qbase_update_json_file_singleString_script_path} -jsonF "${FILE_PATH}" -k "historyVersionJsonFile" -v "${History_Versions_FILE_PATH}"

    echo "将${History_Versions_FILE_PATH}移到项目中，作为项目中的文件使用"
    History_Versions_FILE_Name=${History_Versions_FILE_PATH##*/}
    sh ${bulidScriptCommon_dir_Absolute}/app_info_move_in.sh -sf "${History_Versions_FILE_PATH}" -tf "${WORKSPACE}/flutter_updateversion_kit/assets/data/${History_Versions_FILE_Name}"
    if [ $? != 0 ]; then
        exit_script
    fi
}
NEED_History_Versions_FILE="false" # 是否需要历史版本信息
if [ "${NEED_History_Versions_FILE}" == "true" ]; then
    addAppHistoryVerisonJsonFile
fi


#[在shell脚本中验证JSON文件的语法](https://qa.1r1g.com/sf/ask/2966952551/)
#cat app_info.json
source ${bulidScriptCommon_dir_Absolute}/a_function.sh ${bulidScriptCommon_dir_Absolute} # 为了使用 updatePackageErrorCodeAndMessage
sh ${qbase_json_file_check_script_path} -checkedJsonF "${FILE_PATH}" -resultJsonF "${FILE_PATH}"




function notiMessage() {
    notiContent=$1
    
    if [ -n "${notiContent}" ]; then
        sh "${bulidScriptCommon_dir_Absolute}/noti_new_package.sh" -ll "${notiContent}"
    else
        sh "${bulidScriptCommon_dir_Absolute}/noti_new_package.sh"
    fi
}

function updateProjectCodeEnv() {
    echo "\n"
    updateJsonEnv_scriptFile_Absolute=${bulidScriptCommon_dir_Absolute}/app_info_out_update.sh
    updateIOSCodeEnv_scriptFile_Absolute=${CurrentDIR_Script_Absolute}/update_app_info_ios.sh
    updateAndroidCodeEnv_scriptFile_Absolute=${CurrentDIR_Script_Absolute}/update_app_info_android.sh
    echo "正在执行命令(修改环境)：《 sh ${CurrentDIR_Script_Absolute}/all01_update_env.sh -updateJsonEnvScriptFile \"${updateJsonEnv_scriptFile_Absolute}\" -updateIOSCodeEnvScriptFile \"${updateIOSCodeEnv_scriptFile_Absolute}\" -updateAndroidCodeEnvScriptFile \"${updateAndroidCodeEnv_scriptFile_Absolute}\" -b ${BRANCH} -pl ${PlatformType} -pt $PackageTargetType -pn $PackageNetworkType -saveToF \"${FILE_PATH}\" 》"
    sh ${CurrentDIR_Script_Absolute}/all01_update_env.sh -updateJsonEnvScriptFile "${updateJsonEnv_scriptFile_Absolute}" -updateIOSCodeEnvScriptFile "${updateIOSCodeEnv_scriptFile_Absolute}" -updateAndroidCodeEnvScriptFile "${updateAndroidCodeEnv_scriptFile_Absolute}" -b ${BRANCH} -pl ${PlatformType} -pt $PackageTargetType -pn $PackageNetworkType -saveToF "${FILE_PATH}"
    if [ $? != 0 ]; then
        sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} --log-robottype "error"
        exit_script
    fi

    source ${bulidScriptCommon_dir_Absolute}/a_source_env.sh -appInfoF ${FILE_PATH}
}



function checkCommon_And_updateAppPackageErrorCodeAndMessage_and_IfErrorExit() {
    getCommonScriptResultJSONResultCodeAndMessage
    if [ $? != 0 ]; then
        New_PackageErrorCode=${CommonScriptResultJSON_PackageErrorCodeResult}
        sh ${qbase_update_json_file_singleString_script_path} -jsonF ${FILE_PATH} -k 'package_code' -v "${New_PackageErrorCode}"
    
        New_PackageErrorMessage=${CommonScriptResultJSON_PackageErrorMessageResult}
        sh ${qbase_update_json_file_singleString_script_path} -jsonF ${FILE_PATH} -k 'package_message' -v "${New_PackageErrorMessage}"
        
        sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} --log-robottype "error"
        exit_script
    fi
}



function updateNotificationEnvAfterProjectJsonEnv() {
    #通知
    Notification_Argument_FILE_PATH="${bulidScriptApp_dir_Absolute}/app_notification_robot.json"
    echo "\n"
    echo "NotificatePeople=$NotificatePeople"
    Notification_Argument_MSGTYPE="markdown"
    printf "${BLUE}正在执行命令(通知)《 ${YELLOW}sh ${bulidScriptCommon_dir_Absolute}/notification/notificationParamsJsonFile_deal.sh -notificationArgJsonF \"${Notification_Argument_FILE_PATH}\" -notificationArgPeople \"${NotificatePeople}\" -notificationArgMsgType \"${Notification_Argument_MSGTYPE}\" -envJsonF \"${FILE_PATH}\" ${NC}》\n"
    sh ${bulidScriptCommon_dir_Absolute}/notification/notificationParamsJsonFile_deal.sh -notificationArgJsonF "${Notification_Argument_FILE_PATH}" -notificationArgPeople "${NotificatePeople}" -notificationArgMsgType "${Notification_Argument_MSGTYPE}" -envJsonF "${FILE_PATH}"
    checkCommon_And_updateAppPackageErrorCodeAndMessage_and_IfErrorExit

    #人员
    Product_Personnel_FILE_PATH="${bulidScriptApp_dir_Absolute}/app_product_personnel.json"
    echo "\n"
    printf "${BLUE}正在执行命令(人员)《 ${YELLOW}sh ${bulidScriptCommon_dir_Absolute}/personnel/personnelParamsJsonFile_deal.sh -personnelArgJsonF \"${Product_Personnel_FILE_PATH}\" -envJsonF \"${FILE_PATH}\" ${NC}》\n"
    sh ${bulidScriptCommon_dir_Absolute}/personnel/personnelParamsJsonFile_deal.sh -personnelArgJsonF "${Product_Personnel_FILE_PATH}" -envJsonF "${FILE_PATH}"
    checkCommon_And_updateAppPackageErrorCodeAndMessage_and_IfErrorExit
}



bulidScriptUpload_dir_Absolute="${bulidScriptCommon_dir_Absolute}/upload"

function updateUploadEnv_Pgyer_Cos_AppStore() {
    echo "PgyerUploadUrlType=${PgyerUploadUrlType}"
    if [ "${PgyerUploadUrlType}" == "直接上传到最终地址" ]; then
        PgyerUploadUrlType="toDownUrl"
    elif [ "${PgyerUploadUrlType}" == "先上传到临时地址，通过后再添加到最终地址" ]; then
        PgyerUploadUrlType="toUploadUrl"
    elif [ "${PgyerUploadUrlType}" == "不上传" ]; then
        PgyerUploadUrlType="toNoneUrl"
    else
        printf "${RED}PgyerUploadUrlType=${YELLOW}${PgyerUploadUrlType}${RED} 不正确，请检查${NC}\n"
        exit_script
    fi

    if [ "${PgyerUploadUrlType}" != "toNoneUrl" ]; then
        Pgyer_FILE_PATH="${bulidScriptApp_dir_Absolute}/app_pgyer_info.json"
    
        # "测试蒲公英上传参数"
        Pgyer_Download_FILE_PATH="${Pgyer_FILE_PATH}"
        Pgyer_Download_FILE_KEY=""
        # PgyerUploadUrlType="toUploadUrl"
        # PlatformType="iOS"
        # PackageTargetType="formal"
        # PackageNetworkType="product"
        CurrentBranchName="${BRANCH}"
        pygerArgument=$(sh ${getUploadArg_pgyer_scriptPath} -pgyerDownJsonFPath "${Pgyer_Download_FILE_PATH}" -pgyerDownJsonFKey "${Pgyer_Download_FILE_KEY}" -pgyerUploadUrlType "${PgyerUploadUrlType}" -p "${PlatformType}" -pt "${PackageTargetType}" -pn "${PackageNetworkType}" -curBranchName "${CurrentBranchName}")
        if [ $? != 0 ]; then
            echo "${pygerArgument}"
            exit 1
        fi
        # pgyerArgument='{
        #     "owner": "'"${network_pgyer_owner}"'",
        #     "website_official": "'"${network_pgyer_appOfficialWebsite}"'",
        #     "website_download": "'"${download_website}"'",
        #     "appKey": "'"${network_pgyer_pgyerKey}"'",
        #     "uploadChannelShortcut": "'"${lastUploadShortcut}"'",
        #     "uploadChannelKey": "'"${lastUploadKey}"'",
        #     "downloadChannelShortcut": "'"${lastDownloadShortcut}"'",
        #     "downloadChannelKey": "'"${lastDownloadKey}"'"
        # }'


        # MOVE_PGYER_JSON_FILE_TO_DIR=${WORKSPACE}/pgyer_updateversion_kit/assets/data
        # Pgyer_FILE_Name=${Pgyer_FILE_PATH##*/}
        # sh ${bulidScriptCommon_dir_Absolute}/app_info_move_in.sh -sf "${Pgyer_Download_FILE_PATH}" -tf "${MOVE_PGYER_JSON_FILE_TO_DIR}/${Pgyer_FILE_Name}"
        # if [ $? != 0 ]; then
        #     echo "项目中pgyer_updateversion_kit库需要使用的 ${Pgyer_FILE_PATH} 在移入时候失败"
        #     exit 1
        # fi   
    fi

    
    if [ "${ShouldBackupToCos}" == "true" ]; then
        cosArgument='{
            "region": "ap-shanghai",
            "bucketName": "prod-xhw-image-1302324914",
            "bucketDir": "/mcms/download/app",
            "hostUrl": "https://images.xihuanwu.com"
        }'
    fi

    if [ "${ShouldUploadToAppStore}" == "true" ]; then
        home_appOfficialWebsite="http://h5.yuanwangwu.com/pages-h5/share/download-app"
        if [ "${PlatformType}" == "iOS" ]; then
            real_downloadUrl="https://testflight.apple.com/join/TRKtWdEe"
        else
            real_downloadUrl=""
        fi

        testFlightArgument='{
            "username": "app1@company.com"",
            "password": "app1@companyPasd"",
            "website_official": "'"${home_appOfficialWebsite}"'",
            "website_download":  "'"${real_downloadUrl}"'"
        }'
    fi

    UploadPlatformArgsJson='{
        "pgyer": '${pygerArgument}',
        "cos": '${cosArgument}'
        "testFlight": '${testFlightArgument}'

    }
    '
}


#更新安装包的中英文信息,方便后面直接取值
function updatePackageVersionDescription() {
    echo "\n"
    echo "正在执行命令(更新安装包的中英文信息,方便后面直接取值):《sh ${bulidScriptCommon_dir_Absolute}/update_package_version_description.sh -envJsonF \"${FILE_PATH}\"》"
    sh ${bulidScriptCommon_dir_Absolute}/update_package_version_description.sh -envJsonF "${FILE_PATH}"
}


function checkInputParams() {
    if [ -z "${ChangeLog}" ] || [ "${ChangeLog}" == "-np" ] ; then # "-np" 是为了防止具名参数未填时候，导致的错乱问题
        echo "正在执行命令:《 sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} -ll \"请填写更新说明，否则无法打包\n${ChangeLog}\" --log-robottype \"error\" 》"
        sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} -ll "请填写更新说明，否则无法打包\n${ChangeLog}" --log-robottype "error"
        exit_script
    fi
}


# 打包app
function build_IPA_or_APK() {
    cd $WORKSPACE/wish
    # flutter环境变量设置
    export PUB_HOSTED_URL=https://pub.flutter-io.cn
    export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn
    flutter pub get

    if [ "${PlatformType}" == "iOS" ] ; then
        cd $WORKSPACE/wish/ios
        printf "${BLUE}正在执行命令(进行iOS打包)《 ${YELLOW}python3 $WORKSPACE/bulidScript/build_ios.py 'Runner' 'Runner' 'Release' 'iphoneos' \"${PackageNetworkType}\" \"${PackageTargetType}\" ${BLUE}》${NC}\n"
        python3 $WORKSPACE/bulidScript/build_ios.py 'Runner' 'Runner' 'Release' 'iphoneos' "${PackageNetworkType}" "${PackageTargetType}"
        if [ -f "$WORKSPACE/wish/ios/outputs/IPA/wish.ipa" ] ; then
            ipa_file_path="$WORKSPACE/wish/ios/outputs/IPA/wish.ipa"
        else 
            ipa_file_path="$WORKSPACE/wish/ios/outputs/IPA/Runner.ipa"
        fi
    elif [ "${PlatformType}" == "Android" ] ; then
        #删除上次的apk
        rm -fr "$WORKSPACE/wish/build/app/outputs/apk/release"
        #android打包命令
        cd $WORKSPACE/wish/android
        printf "${BLUE}正在执行命令(进行Android打包)《 ${YELLOW}$WORKSPACE/wish/android/gradlew assembleRelease ${BLUE}》${NC}\n"
        $WORKSPACE/wish/android/gradlew assembleRelease
        ipa_file_path="$WORKSPACE/wish/build/app/outputs/apk/release/wish.apk"
    else
        exit_script
    fi
    cd ${bulidScriptCommon_dir_Absolute}  # 回到公共路径

    export LANG=en_US.UTF-8


    #ipa_file_path="$bulidScriptApp_dir_Absolute/dianzan.svg"
    #ipa_file_path="$WORKSPACE/wish/build/app/outputs/apk/release/1.0.1(11151631).apk"
    if [ ! -f "${ipa_file_path}" ];then
        updatePackageErrorCode ${FILE_PATH} -1
        updatePackageErrorMessage ${FILE_PATH} "failure:编译打包失败，未生成${ipa_file_path}"
        sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} --log-robottype "error"
        exit_script
    fi
}



# 更新包的文件名，方便区别
function renameIPAFile() {
    echo "\n"
    printf "${BLUE}正在执行命令(更新打包出来的包的文件名，方便区别)：《changePackageNameByAppInfoEnvironment ${FILE_PATH} \"${ipa_file_path}\" ${BLUE}》${NC}\n"
    changePackageNameByAppInfoEnvironment ${FILE_PATH} "${ipa_file_path}"
    if [ $? != 0 ]; then
        exit_script
    fi
    ipa_file_path=${ipa_file_path_new}
    sh ${qbase_sed_text_script_path} -appInfoF ${FILE_PATH} -r "package local url" -t "${ipa_file_path}"
}

# 是否应该拷贝输出文件，避免后续打包其会被覆盖掉
function backup_IPA_and_dsym() {
    if [ ${ShouldBackupToLocal} == "true" ]; then
        copy_from_dir_path=$(dirname "$ipa_file_path")
        out_output_dir="${WORKSPACE%/*}/all_ipa_output" # 取WORKSPACE这个文件夹所在的上层文件目录，加上all_ipa_output
        
        appJsonFile_dir=$(dirname "$FILE_PATH")
        upload_continueScriptFile="${appJsonFile_dir}/upload_continue.sh"

        addExtraPaths=""
        addExtraPaths+=("${FILE_PATH}")
        addExtraPaths+=("${upload_continueScriptFile}")
        if [ "${PackageTargetType}" == "formal" ] && [ "${PackageNetworkType}" == "product" ]; then
            DWARF_DSYM_FOLDER_PATH="${WORKSPACE}/wish/ios/outputs/Runner.xcarchive/dSYMs/Runner.app.dSYM"
            addExtraPaths+=("${DWARF_DSYM_FOLDER_PATH}")
        fi
        # echo "=====所有待添加的路径 addExtraPaths =${addExtraPaths[*]}"
        echo "\n"
        printf "${BLUE}正在执行方法(拷贝输出文件到本地，避免后续打包其会被覆盖掉)《 copyAllFileToFrom_andBackUpTo -copyDirFrom \"${copy_from_dir_path}\" -addAppInfoF \"${FILE_PATH}\" -addExtraPaths \"${addExtraPaths[*]}\" -copyDirTo \"${out_output_dir}\" ${BLUE}》${NC}\n"
        copyAllFileToFrom_andBackUpTo -copyDirFrom "${copy_from_dir_path}" -addAppInfoF "${FILE_PATH}" -addExtraPaths "${addExtraPaths[*]}" -copyDirTo "${out_output_dir}"

    fi
}

# 上传
function upload_IPA_or_APK() {
    echo "\n"
    echo "打包成功，准备上传"
    sh ${qbase_sed_text_script_path} -appInfoF ${FILE_PATH} -r "pack doing" -t "pack finished"
    sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} -ll "打包成功，正在上传"

    echo "\n"
    Transporter_USERNAME="app1@company.com"
    Transporter_PASSWORD="djjj-bjkz-rghr-aish"

    Package_Notification_Argument_Current=$(cat ${FILE_PATH} | ${JQ_EXEC} '.package_notification_argument_current') # 由 updateNotificationEnvAfterProjectJsonEnv 所得
    if [ -z "${Package_Notification_Argument_Current}" ] || [ "${Package_Notification_Argument_Current}" == "null" ]; then
        UploadNotificationShowType="None" # None \ Pure \ Detail
    else
        UploadNotificationShowType="Pure" # None \ Pure \ Detail
    fi
    
    printf "${BLUE}正在执行命令(上传)：《 ${YELLOW}sh ${bulidScriptUpload_dir_Absolute}/all_packing_upload.sh -envInfoF \"${FILE_PATH}\" -ipa \"${ipa_file_path}\" -TransporterUserName \"${Transporter_USERNAME}\" -TransporterPassword \"${Transporter_PASSWORD}\" -uploadSupplementJsonF \"${bulidScriptCommon_dir_Absolute}/upload/upload_result_log.json\" -uploadNotificationShowType \"${UploadNotificationShowType}\" ${BLUE}》${NC}\n"
    sh ${bulidScriptUpload_dir_Absolute}/all_packing_upload.sh -envInfoF "${FILE_PATH}" -ipa "${ipa_file_path}" -TransporterUserName "${Transporter_USERNAME}" -TransporterPassword "${Transporter_PASSWORD}" -uploadSupplementJsonF "${bulidScriptCommon_dir_Absolute}/upload/upload_result_log.json" -uploadNotificationShowType "${UploadNotificationShowType}"
    checkCommon_And_updateAppPackageErrorCodeAndMessage_and_IfErrorExit


    # ipa_file_path="${CurrentDIR_Script_Absolute}/App1Enterprise/App1Enterprise.ipa"
    # ipa_file_path="/Users/qian/Project/CQCI/script-qbase/upload_app/App1Enterprise/App1Enterprise.ipa"
    TEST_JSON_FILE="${CurrentDIR_Script_Absolute}/example30_upload_to_all_and_log.json"

    # updateDesString="测试蒲公英上传到指定位置，请勿下载"
    updateDesFromFilePath=${TEST_JSON_FILE}
    updateDesFromFileKey="package_des.chinese"

    # UploadPlatformArgsFilePath=${TEST_JSON_FILE}
    # UploadPlatformArgsFileKey="package_platform_arg"
    # UploadResult_FILE_PATH=${TEST_JSON_FILE}
    # UploadResult_FILE_Key="upload_result"


    # 日志机器人的配置
    LogPostToRobotUrl="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=925776da-1ff4-417a-922a-d5ced384050e"
    LogPostTextHeader="这是上传过程中对日志进行补充的标题"


    # 示例
    log_title "上传ipa到各个平台,平台参数来源于文件"
    # sh ${CommonFun_HomeDir_Absolute}/upload_to_all_byArgFile.sh -ipa "${ipa_file_path}" \
    #     -updateDesString "${updateDesString}" -updateDesFromFilePath "${updateDesFromFilePath}" -updateDesFromFileKey "${updateDesFromFileKey}" \
    #     -uploadArgsFPath "${UploadPlatformArgsFilePath}" -uploadArgsFKey "${UploadPlatformArgsFileKey}" -uploadArgsJson "${UploadPlatformArgsJson}" -uploadResultFKey "${UploadResult_FILE_Key}" \
    #     -LogPostToRobotUrl "${LogPostToRobotUrl}" -LogPostTextHeader "${LogPostTextHeader}"
    #     exit
    responseJsonString=$(sh ${CommonFun_HomeDir_Absolute}/upload_to_all_and_log.sh -ipa "${ipa_file_path}" \
        -updateDesString "${updateDesString}" -updateDesFromFilePath "${updateDesFromFilePath}" -updateDesFromFileKey "${updateDesFromFileKey}" \
        -uploadArgsFPath "${UploadPlatformArgsFilePath}" -uploadArgsFKey "${UploadPlatformArgsFileKey}" -uploadArgsJson "${UploadPlatformArgsJson}" \
        -uploadResultFPath "${UploadResult_FILE_PATH}" -uploadResultFKey "${UploadResult_FILE_Key}" \
        -LogPostToRobotUrl "${LogPostToRobotUrl}" -LogPostTextHeader "${LogPostTextHeader}" \
        )
    if [ $? != 0 ]; then
        echo "${responseJsonString}" # 此时值为错误信息
        exit 1
    fi
    echo "${GREEN}上传ipa到各个平台的脚本执行成功，结果如下:${BLUE}\n${responseJsonString} \n${GREEN}更多详情请查看: ${UploadPlatformArgsFilePath} ${NC}"
}

# 上传符号表
function needUploadDSYM() {
    bugly_config_file_path="${CurrentDIR_Script_Absolute}/dsym/app_pack_info_bugly.json"
    buglyqq_upload_symbol="${CurrentDIR_Script_Absolute}/dsym/buglyqq-upload-symbol/buglyqq-upload-symbol.jar"
    app_info_abspath=${FILE_PATH}
    if [ "${PlatformType}" == "iOS" ]; then
        DWARF_DSYM_FOLDER_PATH="${WORKSPACE}/wish/ios/outputs/Runner.xcarchive/dSYMs/Runner.app.dSYM"
    fi

    if [ ! -d "${DWARF_DSYM_FOLDER_PATH}" ]; then
        echo "📢📢：符号表文件不存在，将为你跳过上传。如需上传，请检查"
    else
        # source ~/.zshrc
        source ${HOME}/.zshrc
        if [ $? != 0 ]; then
            echo "执行命令(激活环境变量)失败:《 source ${HOME}/.zshrc 》"
        fi
        # if [[ $project_dir =~ ^~.* ]]; then
        #     # 如果 $project_dir 以 "~/" 开头，则将波浪线替换为当前用户的 home 目录
        #     project_dir="${HOME}${project_dir:1}"
        # fi
        jdk8
        if [ $? != 0 ]; then
            echo "执行命令(切换到jdk8)失败:《 jdk8 》"
        fi

        java -version
        if [ $? != 0 ]; then
            echo "执行命令(输出java版本)失败:《 java -version 》"
        fi

        printf "${BLUE}正在执行命令(上传符号表):《 ${YELLOW}sh ${bulidScriptCommon_dir_Absolute}/dsym/base_bugly_upload.sh -appBuglyConfigF \"${bugly_config_file_path}\" appBuglyScriptF \"${buglyqq_upload_symbol}\" -appVersionInfoF \"${app_info_abspath}\" -appDSYMF \"${DWARF_DSYM_FOLDER_PATH}\" ${BLUE}》${NC}\n"
        sh ${bulidScriptCommon_dir_Absolute}/dsym/base_bugly_upload.sh -appBuglyConfigF "${bugly_config_file_path}" -appBuglyScriptF "${buglyqq_upload_symbol}" -appVersionInfoF "${app_info_abspath}" -appDSYMF "${DWARF_DSYM_FOLDER_PATH}"
    fi
}

function makeMutiChannelPackage() {
    if [ "${PlatformType}" == "Android" ] ; then
        if [ "${PackageTargetType}" == "formal" ] && [ "${PackageNetworkType}" == "product" ]; then
            _makeMutiChannelPackage_Android huawei xiaomi vivo oppo yingyongbao 360 baidu alibaba general
        else
            _makeMutiChannelPackage_Android huawei xiaomi yingyongbao
        fi
    fi
}

function _makeMutiChannelPackage_Android() {
    VERSION=$(cat ${FILE_PATH} | ${JQ_EXEC} -r ".version")
    BUILD=$(cat ${FILE_PATH} | ${JQ_EXEC} -r ".buildNumber")

    echo "版本号:${VERSION},Build号：${BUILD}"
    VERSION=${VERSION//./_}
    versionName="v${VERSION}(${BUILD})";
    outputName="wish_${versionName}"
    echo "文件名:${outputName}"
    
    channels=("$@")
    for channelName in "${channels[@]}"
    do 
        printf "${RED}正在执行命令(打渠道包$channelName):《 ${YELLOW}sh ${bulidScriptApp_dir_Absolute}/android_channel.sh -c $channelName -p \"$WORKSPACE/wish/build/app/outputs/flutter-apk/app-release.apk\" -n $outputName -v $versionName ${BLUE}》${NC}\n"
        sh ${bulidScriptApp_dir_Absolute}/android_channel.sh -c $channelName -p "$WORKSPACE/wish/build/app/outputs/flutter-apk/app-release.apk" -n $outputName -v $versionName
    done
}


updateProjectCodeEnv

# needSendNoti=false
# if [ "${needSendNoti}" == true ]; then
    updateNotificationEnvAfterProjectJsonEnv
# fi

updateUploadEnv_Pgyer_Cos_AppStore

updatePackageVersionDescription

# checkInputParams
sh ${bulidScriptCommon_dir_Absolute}/noti_new_package.sh -appInfoF ${FILE_PATH} -ll "打包脚本已执行，准备开始打包\n${ChangeLog}"



build_IPA_or_APK
renameIPAFile
backup_IPA_and_dsym
upload_IPA_or_APK
needUploadDSYM
makeMutiChannelPackage
echo 打包完成


:<<!
if [ "${PlatformType}" == "Android" ] && [ "${PackageTargetType}" == "formal" ] && [ "${PackageNetworkType}" == "product" ]; then
    cd $WORKSPACE/bulidScript
    notiMessage "这是Android待加固的审核包,下面额外执行加固操作,并输出渠道包\n${ChangeLog}"
    sh hardeningApk.sh "${ipa_file_path}"
fi
!
echo "所有脚本执行结束"











